<template>
  <div>
    <!-- 面包屑导航区 --------------------------------------------------------->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 ----------------------------------------------------------->
    <el-card>

      <!-- 警告框 --------------------------------------------------------------->
      <el-alert title="添加商品信息" type="info" :closable="false"
          show-icon center> </el-alert>

      <!-- 进度条 --------------------------------------------------------------->
      <el-steps :active="stepActive - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品照片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!----------------------  总表单  ------------------------------->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" 
          label-width="100px" label-position="top">

        <!----------------------  总标签页面  ------------------------------->
        <el-tabs tab-position="left"  v-model="stepActive"
            :before-leave="onBeforeLeave" @tab-click="tabClicked">

          <!----------------------  基本信息  ------------------------------->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader class="cate_select"
                :options="cateList"
                v-model="addForm.goods_cat"
                :props="cateProps"
                @change="onCascaderChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!----------------------  商品参数  ------------------------------->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" 
                :key="item.attr_id">

                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox :label="v" v-for="(v,i) in item.attr_vals"
                      :key="i"  border></el-checkbox>
                </el-checkbox-group>

              <!-- <pre>{{item.attr_vals}}</pre> -->
            </el-form-item>
          </el-tab-pane>

          <!----------------------  商品属性  ------------------------------->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" 
                :key="item.attr_id">
              <el-input v-model="item.attr_vals" ></el-input>
              <!-- <pre>{{item.attr_vals}}</pre> -->
            </el-form-item>

          </el-tab-pane>

          <!----------------------  商品照片  ------------------------------->
          <el-tab-pane label="商品照片" name="3">
            
            <el-upload
              :headers="headerObj"
              :action="uploadURL"
              :on-preview="onPreview"
              :on-remove="onRemove"
              :on-success="onSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>

          </el-tab-pane>

          <!----------------------  商品内容  ------------------------------->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>

            <!-- 添加商品按钮 -->
            <el-button type="primary" class="btnAdd"
              @click="add">添加商品</el-button>
          </el-tab-pane>

        </el-tabs> <!-- /总标签页 -->

      </el-form> <!-- /总表单 -->

    </el-card> <!-- /卡片视图区 -->

    <!----------------------  图片预览  ------------------------------->
    <el-dialog
      title="图片预览" 
      :visible.sync="previewVisible"
      width="50%">
      <img :src="previePath" class="previewImg">      
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash';

export default {
  data(){
    return {
      stepActive: '0',
      // 表单数据绑定
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        // 图片数组
        pics: [],
        // 商品详情
        goods_introduce:'',
        attrs: []

      },
      addFormRules: {
        goods_name: [
          {required: true, message:'请输入商品名称', trigger: 'blur'},
        ],
        goods_price: [
          {required: true, message:'请输入商品价格', trigger: 'blur'},
        ],
        goods_weight: [
          {required: true, message:'请输入商品重量', trigger: 'blur'},
        ],
        goods_number: [
          {required: true, message:'请输入商品数量', trigger: 'blur'},
        ],
        goods_cat: [
           {required: true, message:'请选择商品分类', trigger: 'blur'},
        ]
      },
      // 分类数据
      cateList: [],
      // 级联选择器
      cateProps: {
        expandTrigger: 'hover', 
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },
      // 动态参数数据列表
      manyTableData: [],
      onlyTableData: [],
      // 上传图片路径
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传组件的 headers 请求头对象
      headerObj : {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览URL
      previePath: '',
      // 图片预览 flag
      previewVisible: false,

    }
  },
  created(){
    this.getCateList();
  },
  methods: {
    async getCateList(){
      const {data:res} = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类列表失败！");
      }

      this.cateList = res.data;
    },
    // 级联分类选择器
    onCascaderChange(){
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        this.$message.warning("请选择三级商品分类")
      }
    },
    // tabs
    onBeforeLeave(activeName, oldName){
      if(oldName === '0' && this.addForm.goods_cat.length !== 3){
        this.$message.error("请首先选择商品分类！");
        return false;
      }      
    },
    async tabClicked(tab){
      if (this.addForm.goods_cat.length !== 3){
        return
      }
      // 商品参数标签被点击
      if (tab.name === '1'){
        let id = this.addForm.goods_cat[2];
        const {data:res} = 
            await this.$http.get(`categories/${id}/attributes`,{
              params: {
                sel: 'many'
              }
            });
        if (res.meta.status !== 200) {
          return this.$message.error("获取分类参数信息失败！")
        }   

        // 将 attr_vals 从字符串转为数组
        res.data.forEach(item => {
          let valsStr = item.attr_vals.trim();
          item.attr_vals = valsStr.length>0 ? valsStr.split(' '): []
        });

        this.manyTableData = res.data;
      }
      // 商品属性标签被点击
      if (tab.name === '2'){
        let id = this.addForm.goods_cat[2];
        const {data:res} = 
            await this.$http.get(`categories/${id}/attributes`,{
              params: {
                sel: 'only'
              }
            });
        if (res.meta.status !== 200) {
          return this.$message.error("获取分类参数信息失败！")
        }   

        this.onlyTableData = res.data;
        
        console.log(this.onlyTableData);    // DEBUG
        
      }
    },
    // 处理图片预览
    onPreview(file){
      console.log(this.previePath);    // DEBUG    
      this.previePath = file.response.data.url;
      this.previewVisible = true;
    },
    // 移除图片
    onRemove(file){
      // 1. 获取将要删除的图片的临时路径
      const filePath = file.response.data.tmp_path;
      // 2. 从 pics 数组中， 找到这个图片对应的索引值
      const i = this.addForm.pics.findIndex(x => {
                  x.pic === filePath
                });
      // 3. 调用数组的 splice 方法把图片信息对象从数组中移除
      this.addForm.pics.splice(i, 1);
      
    },
    // 图片上传成功回调函数
    onSuccess(resp){
      // 1. 拼接得到一个图片信息对象
      const picInfo = {pic: resp.data.tmp_path};
      // 2. 将图片信息对象， push 到 pics 数组中
      this.addForm.pics.push(picInfo);
      
    },
    add(){
      // 校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid){
          return this.$message.error("校验未通过。")
        }
        // this.$message.info("valide pass");
        // 执行添加的业务逻辑
        // loadash cloneDeep(obj) 深拷贝
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(',');

        // 清空一下
        this.addForm.attrs = [];
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo);
        });
        // 处理静态属性
        this.onlyTableData.forEach(item =>{
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo);
        });

        form.attrs = this.addForm.attrs;

        console.log(form);    // DEBUG

        // 发起请求，添加商品
        // 商品的名称必须是唯一的
        const {data:res} = await this.$http.post('goods', form);
        if (res.meta.status !== 201) {
          return this.$message.error("添加商品失败");
        }
        this.$message.success("添加商品成功！");
        this.$router.push("/goods");
      });
      
    }

  }
}
</script>

<style scoped>
.cate_select {
  width: 350px;
}
.el-checkbox {
  margin: 0 10px 15px 0!important;
}
.previewImg {
  width: 100%;
}

.btnAdd {
  margin-top: 15px;
}

</style>